package com.zjx.mhxykey;

import android.annotation.SuppressLint;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;

import com.zjx.mhxykey.net.UpNet;
import com.zjx.mhxykey.root.Execute;
import com.zjx.mhxykey.root.RootCmd;
import com.zjx.mhxykey.util.BitmapCutoutUtils;
import com.zjx.mhxykey.util.BitmapStringConverter;
import com.zjx.mhxykey.util.ImageComparator;
import com.zjx.mhxykey.util.ImageLoader;

import java.io.File;
import java.util.Locale;

public class CommandReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if ("COMMAND_EXECUTED".equals(intent.getAction())) {
            // 处理指令执行完成的通知
            Log.d("CommandReceiver", "后台指令已执行");

            // 可以在这里显示通知或做其他处理
            new Thread(() -> screenshots(context)).start();
        }
    }

    private void screenshots(Context context){
        Execute.screenshots(BitmapConfig.screenFilePath(context), new RootCmd.RootCallBack() {
            @Override
            public void result(boolean completed) {
                String key = read(context);
                if (key == null) return;
                Log.d("CommandReceiver", "识别屏幕："+key);
                UpNet.upData(key);
            }
        });
        Log.d("CommandReceiver", "已截屏");
    }


    public String read(Context context){
        StringBuilder sb = new StringBuilder();
        Bitmap screen = ImageLoader.loadFromExternalCache(context,BitmapConfig.screenFileName);
        for (int i = 0; i < 6; i++) {
            Rect rect = new Rect(160 + 68 * i,879,219+ 68 * i,974);
            Rect rect1 = new Rect(rect.left + 8,rect.top + 8,rect.right - 8,rect.bottom - 8);
            Bitmap cut = BitmapCutoutUtils.cutRect(screen,rect1);
            String ss = BitmapStringConverter.bitmapToHexString(cut);
            assert ss != null;
            if (ss.equals(BitmapConfig.keyCode_0)) sb.append(0);
            if (ss.equals(BitmapConfig.keyCode_1)) sb.append(1);
            if (ss.equals(BitmapConfig.keyCode_2)) sb.append(2);
            if (ss.equals(BitmapConfig.keyCode_3)) sb.append(3);
            if (ss.equals(BitmapConfig.keyCode_4)) sb.append(4);
            if (ss.equals(BitmapConfig.keyCode_5)) sb.append(5);
            if (ss.equals(BitmapConfig.keyCode_6)) sb.append(6);
            if (ss.equals(BitmapConfig.keyCode_7)) sb.append(7);
            if (ss.equals(BitmapConfig.keyCode_8)) sb.append(8);
            if (ss.equals(BitmapConfig.keyCode_9)) sb.append(9);
        }
        return sb.toString();
    }
}